﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

using tinterBot.Properties;

namespace tinterBot
{
    static class networkManager
    {
        public static TcpClient netClient = new TcpClient();
        public static Thread netThread = new Thread(messageLoop);

        static void messageLoop()
        {
            netClient.Connect(Settings.Default.server, Settings.Default.port);

            netWrite(string.Format(
                "NICK {0}\r\nUSER {1} {1} {2} :{3}\r\n",
                Settings.Default.nick, Settings.Default.user, Settings.Default.server, Settings.Default.realname));

            while (netClient.Connected)
            {
                string response = netRead();
                Program.ConWrite(response);

                if (Regex.IsMatch(response, "PING :[A-Za-z0-9]*\r\n"))
                {
                    netWrite(Regex.Replace(response, "PING", "PONG"));
                }

                if (Regex.IsMatch(response, string.Format(":{0} 005", Settings.Default.server)))
                {
                    netWrite(string.Format("JOIN {0}\r\n", Settings.Default.channels));
                    if (!string.IsNullOrEmpty(Settings.Default.nsPass))
                        netWrite(string.Format("PRIVMSG nickServ :IDENTIFY {0}\r\n", Settings.Default.nsPass));
                }

                if (Regex.IsMatch(response, ":[A-Za-z0.9@!\\.]* PRIVMSG #[A-Za-z0-9]* :\\?"))
                {
                    libPlugin.BotJob job = new libPlugin.BotJob();
                    job.addedTime = DateTime.Now;
                    job.commandToProcess = response;
                    jobScheduler.jobsToSort.Add(job);
                    jobScheduler.jobThread.Interrupt();
                }
            }
        }

        public static void netWrite(string text)
        {
            Program.ConWrite(text);

            byte[] data = Encoding.UTF8.GetBytes(text);
            netClient.GetStream().Write(data, 0, data.Length);
        }

        static string netRead()
        {
            byte[] buffer = new byte[256];
            StringBuilder message = new StringBuilder();
            NetworkStream netMsg = netClient.GetStream();

            try
            {
                do
                {
                    int bytes = netMsg.Read(buffer, 0, buffer.Length);
                    message.Append(Encoding.UTF8.GetString(buffer, 0, bytes));
                }
                while (netMsg.DataAvailable);
            }
            catch (IOException ex)
            {
                if(Program.conStream.BaseStream != null)
                    Program.ConWrite(ex.Message);
                return "";
            }

            return message.ToString();
        }
    }
}
